import Mock from 'mockjs'

const paramToObj = (url) => {
  const search = url.split('?')[1]
  if (!search) {
    return {}
  }
  return JSON.parse(
    '{"' +
      decodeURIComponent(search)
        .replace(/"/g, '\\"')
        .replace(/&/g, '","')
        .replace(/=/g, '":"') +
      '"}'
  )
}

let list = []
const count = 200
for (let i = 0; i < count; i++) {
  list.push({
    id: Mock.Random.guid(),
    name: Mock.Random.cname(),
    addr: Mock.mock('@county(true)'),
    age: Mock.Random.integer(18, 60),
    birth: Mock.Random.date(),
    sex: Mock.Random.integer(0, 1)
  })
}

export default {
  getUserList: (config) => {
    const { name, page = 1, limit = 20 } = paramToObj(config.url)
    const mockList = list.filter((item) => {
      return !(name && item.name.indexOf(name) < 0)
    })
    //分页
    const pageList = mockList.filter((item, index) => index < limit * page && index >= limit * (page - 1))
    return {
      code: 200,
      data: {
        total: mockList.length,
        items: pageList
      }
    }
  },
  deleteUser: (config) => {
    const { id } = paramToObj(config.url)
    if(!id){
      return {
        code: 400,
        message: 'id不能为空'
      }
    }
    list = list.filter((item) => item.id !== id)
    return {
      code: 200,
      message: '删除成功'
    }
  },
  addUser: (config) => {
    const { name, age, addr, birth, sex } = JSON.parse(config.body)
    list.unshift({
      id: Mock.Random.guid(),
      name: name,
      age: age,
      addr: addr,
      birth: birth,
      sex: sex
    })
    return {
      code: 200,
      message: '添加成功'
    }
  },
  editUser: (config) => {
    const { id, name, age, addr, birth, sex } = JSON.parse(config.body)
    list.some((item) => {
      if (item.id === id) {
        item.name = name
        item.age = age
        item.addr = addr
        item.birth = birth
        item.sex = sex
        return true
      }
    })
    return {
      code: 200,
      message: '修改成功'
    }
  }
}
